package com.ruoyi.common.utils.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : zhenhc
 * @date : 2022-04-17 18:17
 **/
public class HtmlUtils {

    /**
     * 获取网页地址的所有图片
     * @param url url地址
     * @return
     */
    public static List<Map<String,String>> getAllImages(String url){
        try {
            Document document = Jsoup.connect(url).get();
            //使用正则表达式匹配图片png,jpe,jpg,gif
            Elements images = document.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
            List<Map<String, String>> collect = images.stream().map(image -> {
                Map<String, String> map = new HashMap<>();
                map.put("src", image.attr("src"));
                map.put("alt", image.attr("alt"));
                return map;
            }).collect(Collectors.toList());
            return collect;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
